package org.gp.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.gp.core.entity.ReasonSetting;
import org.gp.core.entity.dto.ResponseDTO;
import org.gp.core.mapper.ReasonSettingMapper;
import org.gp.core.service.IReasonSettingService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 原因配置表  服务实现类
 * </p>
 *
 * @author LuoLiang
 * @since 2017-06-04
 */
@Service
public class ReasonSettingServiceImpl extends ServiceImpl<ReasonSettingMapper, ReasonSetting> implements IReasonSettingService {

    @Override
    public ResponseDTO<List<ReasonSetting>> list(String type) {
        ResponseDTO<List<ReasonSetting>> dto = new ResponseDTO<>();

        EntityWrapper<ReasonSetting> ew = new EntityWrapper<>();
        ew.where("label={0}", type);//设置查询黑名单配置类型
        dto.setData(selectList(ew));

        return dto;
    }

    @Override
    public ResponseDTO update(String json, String type) {
        ResponseDTO dto = new ResponseDTO();

        List<ReasonSetting> reasonSettings = JSONObject.parseArray(json, ReasonSetting.class);//把参数先转换为数组

        EntityWrapper<ReasonSetting> ew = new EntityWrapper<>();
        ew.where("label={0}", type);//设置查询黑名单配置类型
        List<Integer> reasonSettingIds = selectList(ew).stream().map(ReasonSetting::getId).collect(Collectors.toList());//查询出数据库中现有的配置的id

        reasonSettings.stream().forEach(reasonSetting -> {//批量更新，并移除已经更新的元素
            insertOrUpdate(reasonSetting);
            if (reasonSettingIds.contains(reasonSetting.getId())) {
                reasonSettingIds.remove(reasonSetting.getId());
            }
        });

        if (!CollectionUtils.isEmpty(reasonSettingIds)) {
            reasonSettingIds.stream().forEach(id -> deleteById(id));//批量删除元素
        }

        return dto;
    }
}
